﻿using System;
using System.Web.Mvc;
using Sharp.DataTransferObject.CMS;
using Sharp.Infrastructure;
using Sharp.Infrastructure.Communication;
using Sharp.Platform.Mvc;
using Sharp.ServiceContracts.CMS;
using Sharp.WebBooter.Areas.CMS.Models;
// ReSharper disable Mvc.ViewNotResolved

namespace Sharp.WebBooter.Areas.CMS.Controllers
{
    public class ArticleController : Controller
    {
        // GET: Control/Article
        public ActionResult Index()
        {
            return View();
        }

        [Permission(Name = "新增", Order = 1)]
        [AutomaticTemplate]
        public ActionResult Create()
        {
            ArticleViewModel articleViewModel = new ArticleViewModel();
            return View(articleViewModel);
        }

        [Permission(Name = "编辑", Order = 2)]
        [AutomaticTemplate]
        public ActionResult Edit(Guid id)
        {
            using (var proxy = new ServiceProxy<ICMSService>())
            {
                var model = proxy.Channel.GetArticleInfo(id).Data.To<ArticleViewModel>();

                return View(model);
            }
        }

        [HttpPost, ValidateInput(false)]
        public JsonResult Save(ArticleDTO vm)
        {
            if (vm == null)
            {
                return Json(new Result() { Err = "提交数据出错。" });
            }
            if (string.IsNullOrEmpty(vm.Title))
            {
                return Json(new Result() { Err = "文章标题不能为空." });
            }
            if (string.IsNullOrEmpty(vm.Content))
            {
                return Json(new Result() { Err = "文章内容不能为空." });
            }

            vm.IsOriginal = true;
            using (var proxy = new ServiceProxy<ICMSService>())
            {
                var res = proxy.Channel.SaveArticle(vm);
                res.RedirectToUrl = Url.Action("Index");

                return Json(res);
            }
        }
        [HttpPost]
        public ActionResult GetPaged(DataTableParameter param)
        {
            using (var proxy = new ServiceProxy<ICMSService>())
            {
                var page = proxy.Channel.GetArticlePaged(param.ToPagingFeature());

                return this.Store(page);
            }
        }

        [HttpPost]
        [Permission(Name = "删除", Order = 3)]
        public JsonResult Delete(Guid[] ids)
        {
            using (var proxy = new ServiceProxy<ICMSService>())
            {
                var res = proxy.Channel.DeleteArticles(ids);
                return Json(res);
            }
        }
    }
}